package Set集合排序;

import java.util.TreeSet;

/*
* 测试类
* */
public class 自然排序Comparable的使用 {
    public static void main(String[] args) {
        /*创建集合对象*/
        TreeSet<Student> ts = new TreeSet<>();
        /*创建学生对象*/
        Student s1 = new Student("xishi", 29);
        Student s2 = new Student("wangzhaojun", 28);
        Student s3 = new Student("diaochan", 30);
        Student s4 = new Student("yangyunhua", 33);
        Student s5 = new Student("linqinxia", 33);
        Student s6 = new Student("linqinxia", 33);
        /*把学生添加到集合*/
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
        /*遍历集合*/
        for (Student s : ts) {
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}
/*
* 学生类
* 实现自然排序，就是让元素所属的类实现Comparable接口，重写comparTo(T o)方法
* */
class Student implements Comparable<Student>{
    private String name;
    private int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    /*自定义排序规则*/
    /*重写方法时，一定要注意排序规则，必须按照要求的主要条件和次要条件来写*/
    @Override
    public int compareTo(Student s) {
        /*按照年龄从小到大进行排序*/
        int num=this.age-s.age;
        /*年龄相同时，按照姓名的字母顺序排序*/
        int num2=num==0?this.name.compareTo(s.name):num;
        return num2;
    }
}